package pers.qianyu.month_202012.date_20201210;

import org.junit.*;

import java.util.*;

/**
 * 47. 全排列 II
 * https://leetcode-cn.com/problems/permutations-ii/
 *
 * @author mizzle rain
 * @date 2020-12-10 20:51
 */
public class PermuteUnique2 {
    /**
     * [优化] 数组代替哈希表
     */
    private List<List<Integer>> res = new ArrayList<>();
    private boolean[] visited;

    public List<List<Integer>> permuteUnique(int[] nums) {
        visited = new boolean[nums.length];
        Arrays.sort(nums);
        ArrayList<Integer> track = new ArrayList<>();
        recur(nums, track);
        return res;
    }

    private void recur(int[] nums, List<Integer> track) {
        if (track.size() == nums.length) {
            res.add(new ArrayList<>(track));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) {
                continue;
            }
            if (i != 0 && nums[i - 1] == nums[i] && visited[i - 1]) {
                continue;
            }
            visited[i] = true;
            track.add(nums[i]);
            recur(nums, track);
            track.remove(track.size() - 1);
            visited[i] = false;
        }
    }

    @Test
    public void test1() {
        int[] arr = {1, 1, 2};
        List<List<Integer>> result = new PermuteUnique2().permuteUnique(arr);
        result.forEach(System.out::println);
    }
}
